//
//  SMButton.swift
//  SmartMachine
//
//  Created by Sherman's iMac on 2019/11/6.
//  Copyright © 2019 Smart. All rights reserved.
//

import Cocoa

class SMButton: NSButton {
 
    var trackArea : NSTrackingArea!
    var _backGroundColor : NSColor? = {
        return NSColor.clear
    }()
    var _mouseInBackGroundColor : NSColor? = {
        return NSColor.clear
    }()
    
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
    }
    
    override func updateTrackingAreas() {
        
        super.updateTrackingAreas()
        
        if trackArea != nil {
            self.removeTrackingArea(trackArea)
        }
        
        trackArea = NSTrackingArea.init(rect: self.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeInKeyWindow], owner: self, userInfo: nil)
        self.addTrackingArea(trackArea)
    }
    
    override func mouseEntered(with event: NSEvent) {
        
        changeBackColor(isMouseIn: true)
    }
    
    override func mouseExited(with event: NSEvent) {
        
        changeBackColor(isMouseIn: false)
    }
    
    override func moveDown(_ sender: Any?) {
        
        changeBackColor(isMouseIn: true)
    }
    
    func changeBackColor(isMouseIn isIn : Bool?) {
        
        if isIn == true {
            self.layer?.backgroundColor = _mouseInBackGroundColor?.cgColor
        } else {
            self.layer?.backgroundColor = _backGroundColor?.cgColor
        }
    }
    
    open func setBackgroundColor(curColor color : NSColor?) {
        if color == nil {
            return
        }
        _backGroundColor = color;
        self.layer?.backgroundColor = _backGroundColor?.cgColor;
    }
    open func setMouseInBackgroundColor(curColor color : NSColor?) {
        if color == nil {
            return
        }
        _mouseInBackGroundColor = color;
    }
}
